//
//  UploadImagesViewController.m
//  FMRecordVideo
//
//  Created by 高波 on 2019/4/16.
//  Copyright © 2019 SF. All rights reserved.
//

#define kRGB(R,G,B) [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1]

#import "UploadImagesViewController.h"
#import "UpImagesCell.h"
#import "UITableViewCell+Utils.h"
#import "HttpServiceWrapper.h"
#import <QCloudCOSXML/QCloudCOSXML.h>
#import <QCloudCore/QCloudCore.h>
#import "SVProgressHUD.h"
@interface UploadImagesViewController () <UITableViewDelegate, UITableViewDataSource, QCloudSignatureProvider>
{
    // 图片和mp3
    NSString *_authorization;
    NSString *_region;
    NSString *_bucket;
    NSArray *_keys;
    NSArray *_mediaIds;
    NSString *_tmpSecretId;
    NSString *_tmpSecretKey;
    NSString *_sessionToken;
    BOOL _signd;
    // 视频
    NSString *_videoSign;
    NSString *_videoName;
    NSString *_videoMediaId;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation UploadImagesViewController

- (instancetype)initWithImages:(NSArray *)images type:(UploadType)type
{
    self = [super init];
    if (self) {
        self.images = images;
        self.uploadType = type;
    }
    
    return self;
}

- (instancetype)initWithAvSetUrl:(NSURL *)url type:(UploadType)type
{
    self = [super init];
    if (self) {
        self.Videourl = url;
        self.uploadType = type;
    }
    
    return self;
}

- (instancetype)initWithMp3Url:(NSURL *)Mp3Url type:(UploadType)type
{
    self = [super init];
    if (self) {
        self.mp3Url = Mp3Url;
        self.uploadType = type;
    }
    
    return self;
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"上传进度";
    UIButton *sure = [UIButton buttonWithType:UIButtonTypeCustom];
    [sure setTitle:@"确定" forState:UIControlStateNormal];
    sure.titleLabel.font = [UIFont systemFontOfSize:14];
    sure.layer.cornerRadius = 5.0f;
    sure.clipsToBounds = YES;
    [sure setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sure setBackgroundColor:kRGB(38, 178, 147)];
    sure.bounds = CGRectMake(0, 0, 50, 20);
    [sure addTarget:self action:@selector(sure) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithCustomView:sure];
    self.navigationItem.rightBarButtonItem = right;
    
    _signd = YES;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc] init];

    
    if (self.uploadType == UploadTypeVideo) {
        [self getVideoSignature];
    }else {
        [self getImageSignature];
    }
}

- (void)getImageSignature
{
    NSString *url = @"https://api.121wty.com/test/jserver/fileUpload/getAuthorization";
    
    NSString *type;
    NSMutableArray *files = [NSMutableArray array];
    if (self.uploadType == UploadTypeMp3) {
        type = @"123.mp3";
        for (NSInteger i = 0; i < 1; i ++) {
            [files addObject: @{@"type" : @(1),
                                @"name" : type
                                }];
        }
        
    }else {
        type = @"123.jpg";
        for (NSInteger i = 0; i < self.images.count; i ++) {
            [files addObject: @{@"type" : @(1),
                                @"name" : type
                                }];
        }
    }
    
    NSDictionary *param = @{
                            @"orgId" : self.orgId,
                            @"files" : files
                            };
    
    NSString *paramStr = [self jsonToString:param];
    [[HttpServiceWrapper instance] POST:url parameters:paramStr session:self.ticket resultBlock:^(BOOL isSucceed, id result) {
        if (isSucceed) {
            _authorization = result[@"authorization"];
            _region = result[@"region"];
            _mediaIds = result[@"mediaIds"];
            _keys = result[@"keys"];
            _bucket = result[@"bucket"];
            _tmpSecretId = result[@"tmpSecretId"];
            _tmpSecretKey = result[@"tmpSecretKey"];
            _sessionToken = result[@"sessionToken"];
            if (_tmpSecretId && _tmpSecretKey && _sessionToken) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self configuration];
                });
            }
            
        }else {
            [self handleWithError:result];
        }
    } withDialog:YES];
}

- (void)configuration
{
    QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
    configuration.appID = @"1252766259";
    configuration.signatureProvider = self;
    QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
    endpoint.regionName = _region;//服务地域名称，可用的地域请参考注释
    configuration.endpoint = endpoint;
    [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
    [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:configuration];
    
    [self.tableView reloadData];
}

- (void) signatureWithFields:(QCloudSignatureFields*)fileds
                     request:(QCloudBizHTTPRequest*)request
                  urlRequest:(NSURLRequest*)urlRequst
                   compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
    //实现签名的过程，我们推荐在服务器端实现签名的过程，具体请参考接下来的 “生成签名” 这一章。
    /*向签名服务器请求临时的 Secret ID,Secret Key,Token*/
    
//    _signd = YES;
    
    QCloudCredential *credential = [QCloudCredential new];
    credential.secretID = _tmpSecretId;
    credential.secretKey = _tmpSecretKey;
    credential.token = _sessionToken;
//    credential.secretID = @"AKIDJOehWqdmPs6A3ncowsZ4LNhuwLcflrk1";
//    credential.secretKey = @"mNn6GNK2ei1PYTEoDObcQJyQejwwmTxG";
    QCloudAuthentationV5Creator *creator = [[QCloudAuthentationV5Creator alloc] initWithCredential:credential];
    QCloudSignature *signature = [creator signatureForData:urlRequst];
    continueBlock(signature, nil);
    
//    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.tableView reloadData];
//    });
}

- (void)getVideoSignature
{
    NSString *url = @"https://api.121wty.com/test/jserver/videoSign";
    NSDictionary *param = @{
                            @"orgId" : self.orgId,
                            };
    NSString *paramStr = [self jsonToString:param];
    
    [[HttpServiceWrapper instance] POST:url parameters:paramStr session:self.ticket resultBlock:^(BOOL isSucceed, id result) {
        if (isSucceed) {
            _videoSign = result[@"sign"];
            _videoName = result[@"fileName"];
            _videoMediaId = result[@"mediaId"];
            dispatch_async(dispatch_get_main_queue(), ^{
               [self.tableView reloadData];
            });
        }else {
            [self handleWithError:result];
        }
    } withDialog:YES];
}

- (NSString *)jsonToString:(id)data {
    if(data == nil) { return nil; }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}




- (void)handleWithError:(NSDictionary *)error
{
    NSError *err = (NSError *)error;
    NSLog(@"%@",err.localizedDescription);
    [SVProgressHUD showInfoWithStatus:err.localizedDescription];
//    [[AppUtils shareInstance] showToast:err.localizedDescription];
}

- (void)sure
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.uploadType == UploadTypeVideo) {
        if (_videoSign) {
            return 1;
        }else {
            return 0;
        }
    }else if (self.uploadType == UploadTypeImages) {
        if (_images.count && _signd && _tmpSecretId) {
            return _images.count;
        }else {
            return 0;
        }
    }else {
        if (_tmpSecretId && _signd) {
            return 1;
        }else {
            return 0;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"UpImagesCell";
    UpImagesCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [UpImagesCell cellFromNib];
    }
    
    if (self.uploadType == UploadTypeImages) {
        cell.type = mediaPhoto;
        cell.bucket = _bucket;
        cell.region = _region;
        cell.key = _keys[indexPath.row];
        cell.image = self.images[indexPath.row];
        
    }else if (self.uploadType == UploadTypeVideo){
        if (_videoSign) {
            cell.videoUrl = self.Videourl;
            cell.type = mediaVideo;
            cell.sign = _videoSign;
            cell.videoName = _videoName;
        }
    }else {
        cell.type = mediaMp3;
        cell.bucket = _bucket;
        cell.region = _region;
        cell.key = _keys[indexPath.row];
        cell.mp3Url = self.mp3Url;
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

@end
